<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2016 http://ilunhui.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 挪窝 <864491238@qq.com>
// +----------------------------------------------------------------------

namespace Admin\Controller;
use Think\Controller;
use Common\Controller\AuthController;
use Think\Auth;
use Vendor\ThinkImage\ThinkImage;
use Com\Wechat;
use Com\WechatAuth;
use Org\Util\PHPZip;

class OrderController extends AuthController {
    private $access_token='';
    public function index(){
        $key=I('key');
        if($key&&$key!=""){
            $map = array(
                'startAdd' =>array('like', "%" . $key . "%"),
                'endAdd'=>array('like', "%" . $key . "%"),
                '_logic'     =>'or',
            );

        }
        $map['status']=array('egt',1);
        $sldate=urldecode(I('reservation',''));//获取格式 2015-11-12 - 2015-11-18
        $arr = explode(" - ",$sldate);//转换成数组
        $arrdateone=strtotime($arr[0]);
        $arrdatetwo=strtotime($arr[1].' 23:55:55');
        if($arrdateone && $arrdatetwo){
            $map['UNIX_TIMESTAMP(ctime)'] = array(array('egt',$arrdateone),array('elt',$arrdatetwo),'AND');
        }

        $Nowpage = $_GET['page']?$_GET['page']:1;
        $limits = 10;// 获取总条数
        $count = M('orders')->where($map)->count();//计算总页面where("UNIX_TIMESTAMP(createtime)>=$startMonth AND UNIX_TIMESTAMP(createtime)<$endMonth AND state=1")
        $allpage = ceil($count / $limits);
        $allpage = intval($allpage);
        $lists = M('orders')->where($map)->page($Nowpage, $limits)->order('id desc')->select();
        $this->assign('Nowpage', $Nowpage);
        $this->assign('allpage', $allpage);
        $this->assign('s',$sldate);
        $this->assign('val',$key);
        //var_dump($_GET['page']);exit;
        if($_GET['page']){
            $this->success($lists);
        }
        
        if($_GET['export_excel']){
             //$lists = M('orders')->where($map)->page($Nowpage, $limits)->order('id desc')->select();
             $lists = M('orders')->where($map)->field('id,startadd,endadd,distance,orderno,time,car,name,mphone,bag_num,items,beizhu,cost,car_fee,costfb,status')->select();
             //首行数据
        

         $firstrow = array (
                           "编号",
                           "出发地",
                           "目的地",
                           "距离",
                           "订单号",
                           "时间",
                           "车型",
                           "姓名",
                           "手机",
                           "行李件数",
                           "大件家具",
                           "备注",
                           "总费用",
                           "车费",
                           "搬运费",
                           "订单状态"
        );

            export($lists, '小型搬家-需要搬运订单表', 'orders', $firstrow);
        }

        $this->display();
    }
    //不需要搬运
    public function nocarry(){

        $key=I('key');

        if($key&&$key!=""){
            $map = array(
                'startAdd' =>array('like', "%" . $key . "%"),
                'endAdd'=>array('like', "%" . $key . "%"),
                '_logic'     =>'or',
            );

        }

        $sldate=urldecode(I('reservation',''));//获取格式 2015-11-12 - 2015-11-18
        $arr = explode(" - ",$sldate);//转换成数组
        $arrdateone=strtotime($arr[0]);
        $arrdatetwo=strtotime($arr[1].' 23:55:55');
        if($arrdateone && $arrdatetwo){
            $map['UNIX_TIMESTAMP(ctime)'] = array(array('egt',$arrdateone),array('elt',$arrdatetwo),'AND');
        }
        $map['status']=array('egt',1);
        if($_GET['export_excel']){
             //$lists = M('orders')->where($map)->page($Nowpage, $limits)->order('id desc')->select();
             $lists = M('order')->where($map)->field('id,startadd,endadd,distance,orderno,time,car,name,mphone,beizhu,cost,status')->select();
             //首行数据
       $firstrow = array (
                           "编号",
                           "出发地",
                           "目的地",
                           "距离",
                           "订单号",
                           "时间",
                           "车型",
                           "姓名",
                           "手机",
                           "备注",
                           "费用",
                           "订单状态"
        );

            export($lists, '小型搬家-不需要搬运订单表', 'order', $firstrow);
        }

        $Nowpage = $_GET['page']?$_GET['page']:1;
        $limits = 10;// 获取总条数
        $count = M('order')->where($map)->count();//计算总页面where("UNIX_TIMESTAMP(createtime)>=$startMonth AND UNIX_TIMESTAMP(createtime)<$endMonth AND state=1")
        $allpage = ceil($count / $limits);
        $allpage = intval($allpage);
        $lists = M('order')->where($map)->page($Nowpage, $limits)->order('id desc')->select();
       
        $this->assign('Nowpage', $Nowpage);
        $this->assign('allpage', $allpage);
        $this->assign('s',$sldate);
        $this->assign('val',$key);
        //var_dump($_GET['page']);exit;
        if($_GET['page']){
            $this->success($lists);
        }
        $this->display();
    }

     public function pro(){

        $key=I('key');

        if($key&&$key!=""){
            $map = array(
                'startAdd' =>array('like', "%" . $key . "%"),
                'endAdd'=>array('like', "%" . $key . "%"),
                '_logic'     =>'or',
            );

        }

        $sldate=urldecode(I('reservation',''));//获取格式 2015-11-12 - 2015-11-18
        $arr = explode(" - ",$sldate);//转换成数组
        $arrdateone=strtotime($arr[0]);
        $arrdatetwo=strtotime($arr[1].' 23:55:55');
        if($arrdateone && $arrdatetwo){
            $map['UNIX_TIMESTAMP(ctime)'] = array(array('egt',$arrdateone),array('elt',$arrdatetwo),'AND');
        }
        if($_GET['export_excel']){
             //$lists = M('orders')->where($map)->page($Nowpage, $limits)->order('id desc')->select();
             $lists = M('order_p')->where($map)->field('id,startadd,endadd,distance,orderno,time,car,name,mphone,beizhu,status')->select();
             //首行数据
        $firstrow = array (
                           "编号",
                           "出发地",
                           "目的地",
                           "距离",
                           "订单号",
                           "时间",
                           "车型",
                           "姓名",
                           "手机",
                           "备注",
                           "订单状态"
        );

            export($lists, '小型搬家-不需要搬运订单表', 'order', $firstrow);
        }

        $Nowpage = $_GET['page']?$_GET['page']:1;
        $limits = 10;// 获取总条数
        $count = M('order_p')->where($map)->count();//计算总页面where("UNIX_TIMESTAMP(createtime)>=$startMonth AND UNIX_TIMESTAMP(createtime)<$endMonth AND state=1")
        $allpage = ceil($count / $limits);
        $allpage = intval($allpage);
        $lists = M('order_p')->where($map)->page($Nowpage, $limits)->order('id desc')->select();
       
        $this->assign('Nowpage', $Nowpage);
        $this->assign('allpage', $allpage);
        $this->assign('s',$sldate);
        $this->assign('val',$key);
        //var_dump($_GET['page']);exit;
        if($_GET['page']){
            $this->success($lists);
        }
        $this->display();
    }


    //会员状态
    public function member_state()
    {
    	$id=I('id');
    	if (empty($id))
        {
    		$this->error('用户不存在',U('index'),1);
    	}
    	$status=M('member_list')->where(array('id'=>$id))->getField('state');//判断当前状态情况
    	if($status==1)
        {
    		$statedata = array('state'=>0);
    		$auth_group=M('member_list')->where(array('id'=>$id))->setField($statedata);
    		$this->success('状态禁止',1,1);
    	}
        else
        {
    		$statedata = array('state'=>1);
    		$auth_group=M('member_list')->where(array('id'=>$id))->setField($statedata);
    		$this->success('状态开启',1,1);
    	}

    }

    //编辑回复信息
    public function edit(){
        $orderid=I('id');
        if (!IS_AJAX){
    		$list=M('orders')->where(array('id'=>$orderid))->find();
    		$this->assign('list',$list);
    		$this->display();
        }else{
            $obj=M('orders');
            $data=$_POST;
            $data['status']=2;
            $obj->save($data);
            $touser=$obj->where('id='.$data['id'])->getField('openid');
            $this->_reply_customer($touser,$data['reply'],'carry',$orderid);
            $this->success('回复成功',U('index'),1);
        }

	}


    public function nocarry_edit(){

        if (!IS_AJAX){
            $list=M('order')->where(array('id'=>I('id')))->find();
            $this->assign('list',$list);
            $this->display();
        }else{
            $obj=M('order');
            $data=$_POST;
            $data['status']=2;
            $obj->save($data);
            $touser=$obj->where('id='.$data['id'])->getField('openid');
            $this->_reply_customer($touser,$data['reply'],'nocarry',$data['id']);
            $this->success('回复成功');
        }

    }


    public function pro_edit(){

        if (!IS_AJAX){
            $list=M('order_p')->where(array('id'=>I('id')))->find();
            $this->assign('list',$list);
            $this->display();
        }else{
            $obj=M('order_p');
            $data=$_POST;
            $data['status']=2;
            $obj->save($data);
            $touser=$obj->where('id='.$data['id'])->getField('openid');
            $this->_reply_customer($touser,$data['reply'],'pro',$data['id']);
            $this->success('回复成功');
        }

    }

    public function showpic(){
        ob_end_clean(); 
        $id=I('id');
        if ($id){
            $list=M('order_p')->where(array('id'=>$id))->field('otherimages')->find();
            $orderno=M('order_p')->where(array('id'=>$id))->field('orderno')->find();
             $file_name=$orderno['orderno'].'.zip';
            $zip = new \ZipArchive();
            $zip->open($file_name, \ZipArchive::OVERWRITE);  
           $list=unserialize($list['otherimages']);
                foreach ($list as $key => $value) {
                    $img_file="Uploads/weixin/".$value.'.jpg';
                    $imglist[]=$img_file;
                    $zip->addFile($img_file); //把文件放入zip 
                }
                $zip->close();//关闭 
header('Content-Description: File Transfer');    
Header("content-type:application/x-zip-compressed");  
header('Content-Disposition: attachment; filename='.basename($file_name));     
header('Content-Transfer-Encoding: binary');     
header('Expires: 0');     
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');     
header('Pragma: public');     
header('Content-Length: ' . filesize($file_name));     
ob_clean();   //清空但不关闭输出缓存 
flush();     
@readfile($file_name);   
@unlink($file_name);//删除打包的临时zip文件。文件会在用户下载完成后被删除 
            
        }

    }



    function downImage($url,$filename="") {
    if($url=="") return false;

    if($filename=="") {
        $ext=strrchr($url,".");
        if($ext!=".gif" && $ext!=".jpg" && $ext!=".png" && $ext!="jpeg") return false;
        $filename=date("YmdHis").$ext;
    }

    ob_start();
    //make file that output from url goes to buffer
    readfile($url);
    //file_get_contents($url);  这个方法不行的！！！只能用readfile
    $img = ob_get_contents();
    ob_end_clean();

    $fp=@fopen($filename, "a");//append
    fwrite($fp,$img);

    fclose($fp);

    return $filename;
}


    function addFileToZip($path,$zip) {
        $handler = opendir($path); //打开当前文件夹由$path指定。
        /*
        循环的读取文件夹下的所有文件和文件夹
        其中$filename = readdir($handler)是每次循环的时候将读取的文件名赋值给$filename，
        为了不陷于死循环，所以还要让$filename !== false。
        一定要用!==，因为如果某个文件名如果叫'0'，或者某些被系统认为是代表false，用!=就会停止循环
        */
        while (($filename = readdir($handler)) !== false) {
        if ($filename != "." && $filename != "..") {
        if (is_dir($path . "/" . $filename)) {
      $this->addFileToZip($path . "/" . $filename, $zip);
        } else { 
        $zip->addFile($path . "/" . $filename);
        }
        }
        }
        @closedir($path);
        }


        public function zip()
        {
                 $zip = new \ZipArchive();
if ($zip->open('images.zip', \ZipArchive::OVERWRITE) === TRUE) {
$this->addFileToZip('Uploads/othercard', $zip); //调用方法，对要打包的根目录进行操作，并将ZipArchive的对象传递给方法
$zip->close(); //关闭处理的zip文件
}
$filename='images.zip';

header("Cache-Control: public"); 
header("Content-Description: File Transfer"); 
header('Content-disposition: attachment; filename='.basename($filename)); //文件名   
header("Content-Type: application/force-download");
header("Content-Transfer-Encoding: binary");
header('Content-Length: '. filesize($filename)); //告诉浏览器，文件大小   
readfile($filename);
//header('Location:/images.zip');
        }





    //删除会员
    public function del(){
        $id=$_REQUEST['id'];
        $list = M('Orders')->where(array('id'=>$id))->delete();
        if($list){
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
    }

     public function nocarry_del(){
        $id=$_REQUEST['id'];
        $list = M('Order')->where(array('id'=>$id))->delete();
        if($list){
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
    }

    public function pro_del(){
        $id=$_REQUEST['id'];
        $list = M('order_p')->where(array('id'=>$id))->delete();
        if($list){
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
    }

    public function pl_del(){
        $orderno=$_REQUEST['id'];
        $res = substr($orderno,0,1);
        if($res=="E"){
          $obj = M('Order');
        }else if($res=="C"){
            $obj = M('Orders');
        }else{
           $obj = M('order_p');
        }
        //$data['orderno']=$_REQUEST['id'];
        $data['pinglunstatus']=-1;
        $res =$obj->where(array('orderno'=>$orderno))->save($data);
        if($res){
            $this->success('删除成功');
        }else{
            $this->error('删除失败');
        }
    }


    public function _reply_customer($touser,$content,$type='',$orderid){
/*$appid='wx9332faa7c9589a0e';
$appsecret='d2c3b99cccae5dd77c00487033919ad2';*/
/*if(!session('token')){
$json_token=http_request("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret);
$access_token=json_decode($json_token,true);
session(array('expire'=>$access_token['expires_in']));
                session('token',$access_token['access_token']);
//获得access_token
$this->access_token=$access_token['access_token'];
            }else{
                $token=session('token');
                $this->access_token=$token;//缓存token
            }*/

$this->access_token=$this->getToken();

    switch ($type) {
        case 'carry':
        $M=M('orders');
        $url='http://nuower.com/index.php/remind/index/id/'.$orderid.'/type/'.$type;
            break;
        case 'nocarry':
         $M=M('order');
         $url='http://nuower.com/index.php/remind/index/id/'.$orderid.'/type/'.$type;
            break;
        case 'pro':
          $M=M('order_p');
          $url='http://nuower.com/index.php/remind/pro/id/'.$orderid.'/type/'.$type;
            break;
        
        default:
            # code...
            break;
    }
$orderinfo=$M->find($orderid);

if ($type=='pro') {
    //模板消息  
    $template=array(
    'touser'=>$touser,
    'template_id'=>"HR5fQD2bsWHdjIDC0WOFErxoJT8G1CJzM5VdBXhMZmA",
    'url'=>$url,
    'topcolor'=>"#7B68EE",
    'data'=>array(
    'first'=>array('value'=>urlencode("尊敬的用户您好,您的订单已得到反馈，请及时查看"),'color'=>"#743A3A"),
    'keyword1'=>array('value'=>urlencode($orderinfo['orderno']),'color'=>'#743A3A'),
    'keyword2'=>array('value'=>urlencode("专业搬家-家庭搬家"),'color'=>'#743A3A'),
    'keyword3'=>array('value'=>urlencode("已预约"),'color'=>'#743A3A'),
    'remark'=>array('value'=>urlencode($content),'color'=>'#FFFFFF'),
    )
    ); 
}else{
    $template=array(
    'touser'=>$touser,
    'template_id'=>"v5Le04NUPBaHyxdNgyKTO0SYXLQgQQuq_7Mkabq3ptA",
    'url'=>$url,
    'topcolor'=>"#7B68EE",
    'data'=>array(
    'first'=>array('value'=>urlencode("你好，已为您分配师傅上门"),'color'=>"#743A3A"),
    'keyword1'=>array('value'=>urlencode($orderinfo['orderno']),'color'=>'#743A3A'),
    'keyword2'=>array('value'=>urlencode($orderinfo['cost']),'color'=>'#743A3A'),
    'keyword3'=>array('value'=>urlencode($orderinfo['driver_name']),'color'=>'#743A3A'),
    'keyword4'=>array('value'=>urlencode($orderinfo['driver_mobile']),'color'=>'#743A3A'),
    'keyword5'=>array('value'=>urlencode($orderinfo['driver_gotime']),'color'=>'#743A3A'),
    'remark'=>array('value'=>urlencode($content),'color'=>'#FFFFFF'),
    )
    ); 

}


$json_template=json_encode($template);
//echo $json_template;
//echo $this->access_token;
$url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$this->access_token;
$res=http_request($url,urldecode($json_template));
//if ($res[errcode]==0) echo '模板消息发送成功!';
//print_r($res);

}



  public function tui_pinglun(){

$orderid=I('id');
$type=I('type');
/*$appid='wx9332faa7c9589a0e';
$appsecret='d2c3b99cccae5dd77c00487033919ad2';*/
/*if(!session('token')){
$json_token=http_request("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret);
$access_token=json_decode($json_token,true);
 session(array('expire'=>$access_token['expires_in']));
                session('token',$access_token['access_token']);
//获得access_token
$this->access_token=$access_token['access_token'];
            }else{
                $token=session('token');
                $this->access_token=$token;//缓存token
            }*/

$getToken=$this->getToken();

$this->access_token=$getToken;
    switch ($type) {
        case 'carry':
        $M=M('orders');
            break;
        case 'nocarry':
         $M=M('order');
            break;
        case 'pro':
          $M=M('order_p');
            break;
        
        default:
            # code...
            break;
    }
$pl['id']=$orderid;
$pl['pinglunstatus']=2;
$save=$M->save($pl);
$orderinfo=$M->find($orderid);
$touser=$orderinfo['openid'];
//模板消息  
$template=array(
'touser'=>$touser,
'template_id'=>"7guN2IfCGE8GCxyqZpD_DKOHLWE7YhnYeb_ZjwOkWUo",
'url'=>'http://nuower.com/index.php/pinglun/index/id/'.$orderid.'/type/'.$type,
'topcolor'=>"#7B68EE",
'data'=>array(
'first'=>array('value'=>urlencode("尊敬的用户您好,您的订单完成，请对挪窝儿进行评价"),'color'=>"#743A3A"),
'keyword1'=>array('value'=>urlencode($orderinfo['orderno']),'color'=>'#743A3A'),
'keyword2'=>array('value'=>urlencode($orderinfo['cost']),'color'=>'#743A3A'),
'remark'=>array('value'=>urlencode($content),'color'=>'#FFFFFF'),
)
);
$json_template=json_encode($template);
//echo $json_template;
//echo $this->access_token;
$url="https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$this->access_token;
$res=http_request($url,urldecode($json_template));
echo($res);


}


public function getToken()
{   
    $data = json_decode(get_php_file("access_token.php"));

    if ($data->expire_time < time()) {
       $json_token=http_request("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".appid."&secret=".appsecret);
$access_token=json_decode($json_token,true);
//获得access_token
$access_token=$access_token['access_token'];
      if ($access_token) {
        $data->expire_time = time() + 7000;
        $data->access_token = $access_token;
      set_php_file("access_token.php", json_encode($data));
      }
    } else {

     $access_token = $data->access_token;
    }
    return $access_token;
    
}

public function pl_list()
{   
     $key=I('key');

        if($key&&$key!=""){
            $map = array(
                'user_nickname' =>array('like', "%" . $key . "%"),
                'pl_desc'=>array('like', "%" . $key . "%"),
                '_logic'     =>'or',
            );

        }

        $sldate=urldecode(I('reservation',''));//获取格式 2015-11-12 - 2015-11-18
        $arr = explode(" - ",$sldate);//转换成数组
        $arrdateone=strtotime($arr[0]);
        $arrdatetwo=strtotime($arr[1].' 23:55:55');
        if($arrdateone && $arrdatetwo){
            $map['UNIX_TIMESTAMP(pl_addtime)'] = array(array('egt',$arrdateone),array('elt',$arrdatetwo),'AND');
        }
    $map['pinglunstatus']=1;
    $p_plist=M('order_p')->where($map)->field('id,orderno,pl_desc,headimgurl,user_nickname,pl_addtime,pinglunstatus')->select();
    $e_plist=M('order')->where($map)->field('id,orderno,pl_desc,headimgurl,user_nickname,pl_addtime,pinglunstatus')->select();
    $c_plist=M('orders')->where($map)->field('id,orderno,pl_desc,headimgurl,user_nickname,pl_addtime,pinglunstatus')->select();

    $list=array_merge($p_plist,$e_plist,$c_plist);
      $Nowpage = $_GET['page']?$_GET['page']:1;
        $limits = 10;// 获取总条数
        $count =count($list);
        $start=($Nowpage-1)*$limits;

        $lists=array_splice($list,$start,$limits);//获取二维数组中坐标从5开始的3条记录 
        foreach($lists as $k=>$v)
        {
            $lists[$k]['pl_addtime']=date('Y年m月d日',$v['pl_addtime']);
        }
        $allpage = ceil($count / $limits);
        $allpage = intval($allpage);
       
        $this->assign('Nowpage', $Nowpage);
        $this->assign('allpage', $allpage);
        $this->assign('s',$sldate);
        $this->assign('val',$key);
        if($_GET['page']){
            $this->success($lists);
        }

    $this->assign('list',$list);
   $this->display();

}




}
